package com.longkier.gx_library_springboot.BigModelSocket;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.Setter;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;

public class BigModelNew extends WebSocketListener {
    // 各版本的hostUrl及其对应的domian参数，具体可以参考接口文档 https://www.xfyun.cn/doc/spark/Web.html
    // Spark Lite      https://spark-api.xf-yun.com/v1.1/chat      domain参数为lite
    // Spark Pro       https://spark-api.xf-yun.com/v3.1/chat      domain参数为generalv3
    // Spark Pro-128K  https://spark-api.xf-yun.com/chat/pro-128k  domain参数为pro-128k
    // Spark Max       https://spark-api.xf-yun.com/v3.5/chat      domain参数为generalv3.5
    // Spark Max-32K   https://spark-api.xf-yun.com/chat/max-32k   domain参数为max-32k
    // Spark4.0 Ultra  https://spark-api.xf-yun.com/v4.0/chat      domain参数为4.0Ultra

    public static final String hostUrl = "https://spark-api.xf-yun.com/v3.5/chat";
    public static final String domain = "generalv3.5";
    public static final String appid = "afc1fd2d";
    public static final String apiSecret = "MDVmOTQ0NmY0OTgyOTUyNjU1NTk4Njc4";
    public static final String apiKey = "22b2c9d741c0ccba9b1f57caa50d678c";

    public static List<RoleContent> historyList = new ArrayList<>(); // 对话历史存储集合

    public static String totalAnswer=""; // 大模型的答案汇总

    public static  String NewQuestion = "";

    private static final Logger logger = LoggerFactory.getLogger(BigModelNew.class);

    public static final Gson gson = new Gson();

    // 个性化参数
    @Getter
    private final String userId;
    @Getter
    private Boolean wsCloseFlag;
    private final WebSocketSession frontendSession;

    public static Boolean totalFlag=true; // 控制提示用户是否输入
    private CountDownLatch latch;

    // 构造函数
    public BigModelNew(String userId, Boolean wsCloseFlag, CountDownLatch latch, WebSocketSession frontendSession) {
        this.userId = userId;
        this.wsCloseFlag = wsCloseFlag;
        this.latch = latch != null ? latch : new CountDownLatch(1); // 增加空值保护
        this.frontendSession = frontendSession;
    }

    // 测试主函数
//    public static void main(String[] args) throws Exception {
//        // 个性化参数入口，如果是并发使用，可以在这里模拟
//        while (totalFlag || !NewQuestion.isEmpty()) {
//            if (totalFlag) {
//                Scanner scanner = new Scanner(System.in);
//                System.out.print("我：");
//                totalFlag = false;
//                NewQuestion = scanner.nextLine();
//                if (NewQuestion.equalsIgnoreCase("exit")) {
//                    break; // 允许用户通过输入 "exit" 来退出程序
//                }
//                // 构建鉴权url
//                String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
//                OkHttpClient client = new OkHttpClient.Builder().build();
//                String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
//                Request request = new Request.Builder().url(url).build();
//                for (int i = 0; i < 1; i++) {
//                    totalAnswer = "";
//                    client.newWebSocket(request, new BigModelNew(i + "", false, new CountDownLatch(1), null));
//                }
//            } else {
//                Thread.sleep(200);
//            }
//        }
//    }

    public void processQuestion() {
        try {
            String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
            OkHttpClient client = new OkHttpClient.Builder().build();
            String url = authUrl.replace("http://", "ws://")
                    .replace("https://", "wss://");
            Request request = new Request.Builder().url(url).build();
            if (this.latch == null) {
                this.latch = new CountDownLatch(1);
            }
            client.newWebSocket(request, this);
        } catch (Exception e) {
            logger.error("创建WebSocket连接失败: {}", e.getMessage());
        }
    }

    public static boolean canAddHistory(){  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length=0;
        for(RoleContent temp:historyList){
            history_length=history_length+temp.content.length();
        }
        if(history_length>12000){
            historyList.remove(0);
            historyList.remove(1);
            historyList.remove(2);
            historyList.remove(3);
            historyList.remove(4);
            return false;
        }else{
            return true;
        }
    }

    // 修改 MyThread 类中的逻辑
    class MyThread extends Thread {
        private final WebSocket webSocket;

        public MyThread(WebSocket webSocket) {
            this.webSocket = webSocket;
        }

        public void run() {
            try {
                JSONObject requestJson=new JSONObject();

                JSONObject header=new JSONObject();  // header参数
                header.put("app_id",appid);
                header.put("uid",UUID.randomUUID().toString().substring(0, 10));

                JSONObject parameter=new JSONObject(); // parameter参数
                JSONObject chat=new JSONObject();
                chat.put("domain",domain);
                chat.put("temperature",0.5);
                chat.put("max_tokens",4096);
                parameter.put("chat",chat);

                JSONObject payload=new JSONObject(); // payload参数
                JSONObject message=new JSONObject();
                JSONArray text=new JSONArray();

                // 历史问题获取
                if(!historyList.isEmpty()){
                    for(RoleContent tempRoleContent:historyList){
                        text.add(JSON.toJSON(tempRoleContent));
                    }
                }

                // 最新问题
                RoleContent roleContent= new RoleContent();
                roleContent.role="user";
                roleContent.content=NewQuestion;
                text.add(JSON.toJSON(roleContent));
                historyList.add(roleContent);

                message.put("text",text);
                payload.put("message",message);

                requestJson.put("header",header);
                requestJson.put("parameter",parameter);
                requestJson.put("payload",payload);
                // System.err.println(requestJson); // 可以打印看每次的传参明细
                webSocket.send(requestJson.toString());

                // 使用 CountDownLatch 等待服务端返回完毕后关闭
                latch.await(); // 等待主线程的通知
                webSocket.close(1000, "");
            } catch (Exception e) {
                logger.error("大模型发生异常: {}", e.getMessage(), e);
            }
        }
    }

    @Override
    public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
        super.onOpen(webSocket, response);
        //测试输出头
//        System.out.print("大模型：");
        MyThread myThread = new MyThread(webSocket);
        myThread.start();
    }
    private static final StringBuilder totalAnswerBuilder = new StringBuilder();

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
            System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
            webSocket.close(1000, "");
        }
        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
            // 实时发送每个分片
            if (frontendSession != null && frontendSession.isOpen()) {
                JSONObject response = new JSONObject();
                response.put("content", temp.content);
                response.put("streamId", this.userId); // 使用当前用户ID作为流ID
                response.put("isEnd", myJsonParse.header.status == 2);

                try {
                    frontendSession.sendMessage(new TextMessage(response.toJSONString()));
                } catch (IOException e) {
                    logger.error("消息发送失败: {}", e.getMessage());
                }
            }
            totalAnswerBuilder.append(temp.content);
        }
        if (myJsonParse.header.status == 2) {
            if (frontendSession != null && frontendSession.isOpen()) {
                JSONObject response = new JSONObject();
                response.put("content", "");
                response.put("streamId", this.userId);
                response.put("isEnd", true);
                try {
                    frontendSession.sendMessage(new TextMessage(response.toJSONString()));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            //测试输出尾
//            System.out.println();
//            System.out.println("*************************************************************************************");
            // 可以关闭连接，释放资源
            if(canAddHistory()){
                RoleContent roleContent= new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswerBuilder.toString());
                historyList.add(roleContent);
            }else{
                historyList.remove(0);
                RoleContent roleContent= new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswerBuilder.toString());
                historyList.add(roleContent);
            }
            wsCloseFlag = true;
            latch.countDown(); // 通知主线程可以继续执行
            // 重置 totalAnswerBuilder 以便下一次使用
            totalAnswerBuilder.setLength(0);
        }
    }

    @Override
    public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                if (response.body() != null) {
                    System.out.println("onFailure body:" + response.body().string());
                }
                if (101 != code) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            logger.error("大模型发生异常: {}", e.getMessage(), e);
        }
    }


    // 鉴权方法
    @NotNull
    public static String getAuthUrl(String hostUrl, String apiKey, @NotNull String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }

    //返回的json结果拆解
    public static class JsonParse {
        public Header header;
        public Payload payload;
    }

    public static class Header {
        public int code;
        public int status;
        String sid;
    }

    public static class Payload {
        public Choices choices;
    }

    public static class Choices {
        public List<Text> text;
    }

    public static class Text {
        public String role;
        public String content;
    }
    @Setter
    @Getter
    public static class RoleContent{
        String role;
        String content;

    }
}